package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.article.client.ArticleClient;
import com.usian.common.constants.message.FollowBehaviorConstants;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.JsonUtils;
import com.usian.model.article.dtos.AuthorDto;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.user.entity.ApUser;
import com.usian.user.entity.ApUserFan;
import com.usian.user.entity.ApUserFollow;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.IApUserFanService;
import com.usian.user.service.IApUserFollowService;
import com.usian.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-05
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {
    @Autowired
    private IApUserFollowService apUserFollowService;

    @Autowired
    private IApUserFanService apUserFanService;

    @Autowired
    private ArticleClient articleClient;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 关注和取消关注
     * @param dto
     */


    @Override
    public void follow(UserRelationDto dto) {
        if (dto==null || dto.getOperation()>1 || dto.getOperation()<0){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"参数不可用");
        }
        Integer authorId = dto.getAuthorId();
        if (authorId==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"作者参数异常");
        }
        AuthorDto authorDto = articleClient.findById(authorId);
        if (authorDto==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"该作者不存在");
        }
        //作者关联的app用户id
        Integer followId = authorDto.getUserId();
        //获取当前用户的id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (followId==null||userId==null){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN,"请去登录");
        }
        //判断是关注还是取消关注
        if (dto.getOperation()==1){
            //关注
            followUser(userId,followId,dto.getArticleId());
        }else if (dto.getOperation()==0){
            //取消关注
            cancelFollowUser(userId,followId);
        }
    }

    @Override
    public ApUserFollow findByUserIdAndFollowId(Integer userId, Integer followId) {
        QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApUserFollow::getUserId,userId).eq(ApUserFollow::getFollowId,followId);
        ApUserFollow apUserFollow = apUserFollowService.getOne(queryWrapper);
        return apUserFollow;
    }


    /**
     * 取消关注
     * @param userId
     * @param followId
     */
    @Transactional
    public void cancelFollowUser(Integer userId, Integer followId) {
        LambdaQueryWrapper<ApUserFollow> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApUserFollow::getUserId,userId).eq(ApUserFollow::getFollowId,followId);
        boolean b = apUserFollowService.remove(lambdaQueryWrapper);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除关注数据失败");
        }
        LambdaQueryWrapper<ApUserFan> fanQueryWrapper = new LambdaQueryWrapper<>();
        fanQueryWrapper.eq(ApUserFan::getFansId,userId).eq(ApUserFan::getUserId,followId);
        //删除粉丝数据
        boolean b1 = apUserFanService.remove(fanQueryWrapper);
        if(!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除粉丝数据失败");
        }
    }

    /**
     * 关注
     * @param userId
     * @param followId
     * @param articleId
     */
    @Transactional
    public void followUser(Integer userId, Integer followId, Long articleId) {
        //查询关注的作者是否存在
        ApUser apUser = getById(followId);
        if (apUser==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的作者不存在");
        }
        //存在的话去查询是否已经关注该作者
        LambdaQueryWrapper<ApUserFollow> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApUserFollow::getUserId,userId).eq(ApUserFollow::getFollowId,followId);
        int count = apUserFollowService.count(lambdaQueryWrapper);
        if (count>0){
            new LeadException(AppHttpCodeEnum.SERVER_ERROR,"已经关注过该作者");
        }
        //创建作者信息
        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setUserId(userId);
        userFollow.setFollowId(followId);
        userFollow.setFollowName(apUser.getName());
        userFollow.setLevel(0);
        userFollow.setIsNotice(true);
        userFollow.setCreatedTime(new Date());
        boolean b = apUserFollowService.save(userFollow);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存关注数据失败");
        }

        //查询粉丝是否存在
        ApUser fanUser = this.getById(userId);
        if (fanUser==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"查询的粉丝不存在");
        }
        LambdaQueryWrapper<ApUserFan> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(ApUserFan::getFansId,userId).eq(ApUserFan::getUserId,followId);
        int count1 = apUserFanService.count(lambdaQueryWrapper1);
        if (count1>0){
            new LeadException(AppHttpCodeEnum.SERVER_ERROR,"已经有该粉丝");
        }
        if(count1==0){
            //记录粉丝数据
            ApUserFan userFan = new ApUserFan();
            userFan.setUserId(followId);
            userFan.setFansId(userId);
            userFan.setFansName(fanUser.getName());
            userFan.setLevel(0);
            userFan.setCreatedTime(new Date());
            userFan.setIsDisplay(true);
            userFan.setIsShieldComment(false);
            userFan.setIsShieldLetter(false);
            boolean b1 = apUserFanService.save(userFan);
            if(!b1){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存粉丝数据失败");
            }
        }
        /* 记录关注行为 发送kafka消息*/
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setFollowId(followId);
        dto.setArticleId(articleId);
        dto.setUserId(userId);
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JsonUtils.toString(dto));
    }
}
